const lowerUA = window.navigator.userAgent.toLowerCase()

const getTopHeight = () => {
  let system = uni.getSystemInfoSync() ///微信api方法
  //获取胶囊信息
  let menu = wx.getMenuButtonBoundingClientRect()
  let systemBar = system.statusBarHeight //状态栏高度
  let navigationBar = (menu.top - system.statusBarHeight) * 2 + menu.height //胶囊高度
  return {
    allHeight: systemBar + navigationBar,
    sysBarHeight: systemBar,
    navBarHeight: navigationBar,
  }
}

const showToast = function (title, type = 'success', duration = 3000) {
  this.$refs.uToast.show({
    title,
    type,
    duration,
  })
}

function topTips(title, type = 'success', duration = 3000) {
  this.$refs.uTips.show({ title, type, duration })
}

//文件上传处理
const uploadFile = function (filePath, data = {}) {
  let fullUrl = getApp().globalData.BASE_URL + '/sys/common/upload'
  let token = uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: fullUrl,
      filePath: filePath,
      name: 'file',
      formData: data,
      header: {
        'X-Access-Token': token,
      },
      success: res => {
        resolve(res)
        // if (res.statusCode == 413) {
        // 	getApp().showToast('图片太大啦,请选择其他图片')
        // 	wx.hideLoading();
        // 	return;
        // }
        // let data = JSON.parse(res.data);
        // if (data.success) {
        // 	resolve(data)
        // 	wx.hideLoading()
        // } else {
        // 	getApp().showToast(data.message);
        // 	reject(res);
        // }
        // wx.hideLoading()
      },
      fail(error) {
        uni.hideLoading()
        // getApp().showToast('请求失败')
        reject(error)
      },
    })
  })
}

const formatDate = function (date, fmt = 'yyyy-MM-dd hh:mm:ss') {
  var o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  return fmt
}

// 判断是否为微信环境
const isWechat = () => {
  // 微信环境标识符 && 不是企业微信环境
  return lowerUA.includes('micromessenger') && !lowerUA.includes('wxwork')
}
const isWxwork = () => lowerUA.includes('wxwork') // 企业微信
const isDing = () => lowerUA.includes('dingtalk') // 钉钉
function companyParams({ companyId, clientId, corpId } = {}) {
  // getter
  if (!companyId && !clientId && !corpId) {
    return { companyId: uni.getStorageSync('companyId') ?? '', clientId: uni.getStorageSync('clientId') ?? '', corpId: uni.getStorageSync('corpId') ?? '' }
  }
  // setter
  if (companyId) uni.setStorageSync('companyId', companyId)
  if (clientId) uni.setStorageSync('clientId', clientId)
  if (corpId) uni.setStorageSync('corpId', corpId)
}

/**
 * 四舍五入保留小数位数
 * @param {number} value 保留值
 * @param {number} saveDigit 保留位数
 * @returns {number}
 */
function digitRound(value, saveDigit = 2) {
  let res = value
  const digit = (String(value).split('.')[1] || []).length
  if (digit > 0) {
    // 非整数
    const removeDigit = digit - saveDigit
    res = Math.round(Number(value * Math.pow(10, digit)).toFixed(0) / Math.pow(10, removeDigit)) / Math.pow(10, saveDigit)
  }
  return Number(Number(res).toFixed(saveDigit))
}

/**
 * 简单去除浮点精度计算
 * @param {Array|Arguments} 计算的数据集合
 * @param {String} 计算方式 +加 -减 *乘
 * @returns 计算结果
 */
function jsCompute() {
  const isArr = Array.isArray(arguments[0])
  let numList = isArr ? arguments[0] : Array.prototype.slice.call(arguments, 0, arguments.length - 1)
  numList = numList.map(num => Number(num))
  const type = isArr ? arguments[1] : arguments[arguments.length - 1] // 计算类型

  const digitList = numList.map(num => (String(num).split('.')[1] || []).length)
  const maxDigit = Math.max(...digitList) // 最大小数位位数
  const maxN = Math.pow(10, maxDigit) // 最大指数
  const n_numList = numList.map(_ => Number((_ * maxN).toFixed())) // 指数倍后 numList
  switch (type) {
    case '+':
      return n_numList.reduce((pre, cur) => pre + cur, 0) / maxN
    case '-':
      return n_numList.reduce((pre, cur) => pre - cur) / maxN
    case '*':
      return n_numList.reduce((pre, cur) => pre * cur, 1) / Math.pow(10, maxDigit * numList.length)
    default:
      return
  }
}

/**
 * 防抖
 * @param {function} func
 * @param {number} wait 防抖时间
 * @param {boolean} immediate 第一次立即执行
 */
function debounce(func, wait = 500, immediate) {
  let timeout
  return function () {
    const context = this,
      args = arguments
    const later = function () {
      timeout = null
      if (!immediate) {
        func.apply(context, args)
      }
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) {
      func.apply(context, args)
    }
  }
}
/**
 * 节流
 * @param {function} func
 * @param {number} delay 节流间隔时间
 * @returns
 */
function throttle(func, delay = 500) {
  let prev = Date.now()
  return function () {
    const context = this
    const args = arguments
    const now = Date.now()
    if (now - prev >= delay) {
      func.apply(context, args)
      prev = Date.now()
    }
  }
}

module.exports = {
  getTopHeight, //获取手机顶部状态栏和胶囊的高度
  showToast, //轻文本提示框
  topTips,
  uploadFile, //文件上传
  formatDate, //文件上传
  isWechat, // 微信环境
  isWxwork, // 企业微信环境
  isDing, // 钉钉环境
  companyParams, // 企业参数 getter setter
  digitRound,
  jsCompute,
  debounce,
  throttle,
}
